package com.yfl.logistics.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfl.logistics.pojo.MsgObject;
import com.yfl.logistics.pojo.Role;
import com.yfl.logistics.pojo.User;
import com.yfl.logistics.service.impl.RoleServiceImpl;
import com.yfl.logistics.service.impl.UserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2020-06-13
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    //注入角色
    @Autowired
    private RoleServiceImpl roleService;


    //管理员页面跳转
    @RequiresPermissions("admin:adminPage")
    @GetMapping("/adminPage")
    public String adminPage() {

        return "adminPage";
    }


    //分页查询操作
    @RequiresPermissions("admin:list")
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> list(@RequestParam(defaultValue = "1") Integer pageNum,
                                    @RequestParam(defaultValue = "10") Integer pageSize,
                                    String keyword) {

        //创建分页插件
        IPage<User> page = new Page<>(pageNum, pageSize);

        //创建条件查询对象
        QueryWrapper wq = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            wq.like("username", keyword);
            wq.or();
            wq.like("realname", keyword);
            wq.or();
            wq.like("r.rolename",keyword);
        }

        IPage<User> iPage = userService.selectAdminRole(page, wq);

        Map<String, Object> map = new HashMap<>();
        map.put("total", iPage.getTotal());
        map.put("rows", iPage.getRecords());

        return map;
    }

    //删除操作
    @RequiresPermissions("admin:delete")
    @GetMapping("/delete")
    @ResponseBody
    public MsgObject delect(Integer userId) {

        QueryWrapper<User> wq = new QueryWrapper<>();
        wq.eq("user_id", userId);
        boolean remove = userService.remove(wq);
        MsgObject msgObject = new MsgObject();
        if (remove) {
            msgObject.setCode(1);
            msgObject.setMsg("删除成功");
        } else {
            msgObject.setCode(0);
            msgObject.setMsg("失败");
        }

        return msgObject;
    }

    //添加/编辑页面跳转
    //共享角色信息
    @GetMapping("/adminEdit")
    public String adminEdit(Integer userId, Model m) {

        if (userId == null) {
            //共享角色信息
            List<Role> list = roleService.list();
            m.addAttribute("roles", list);

            return "adminEdit";
        }
        QueryWrapper<User> wq = new QueryWrapper<>();
        wq.eq("user_id", userId);
        User user = userService.getOne(wq);
        m.addAttribute("user", user);

        //共享角色信息
        List<Role> list = roleService.list();
        m.addAttribute("roles", list);

        return "adminEdit";
    }


    //添加用户
    @RequiresPermissions("admin:insert")
    @PostMapping("/insert")
    @ResponseBody
    public MsgObject insertUser(User user) {

        //生成盐
        String salt = UUID.randomUUID().toString().substring(0, 5);
        //设置盐
        user.setSalt(salt);
        //使用MD5加密
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
        //设置加密之后的密码
        user.setPassword(md5Hash.toString());
        if (user.getUserId() == null){
            //设置注册时间
            user.setCreateDate(LocalDate.now());
        }


        boolean save = userService.saveOrUpdate(user);

        MsgObject msgObject = new MsgObject();
        if (save) {
            msgObject.setMsg("操作成功");
            msgObject.setCode(1);
        } else {
            msgObject.setMsg("操作失败");
            msgObject.setCode(2);
        }
        return msgObject;
    }

    //检查用户名是否重复
    @RequiresPermissions("admin:admin:checkUsername")
    @PostMapping("/checkUser")
    @ResponseBody
    public Boolean checkUser(String username) {

        QueryWrapper<User> wq = new QueryWrapper<>();
        wq.eq("username", username);
        User user = userService.getOne(wq);

        if (user != null) {
            return false;
        }
        return true;
    }


    //批量删除
    @RequiresPermissions("admin:delete")
    @GetMapping("/delusers")
    @ResponseBody
    public MsgObject delusers(@RequestParam Integer[] userIds) {

        boolean removeByIds = userService.removeByIds(Arrays.asList(userIds));

        MsgObject msgObject = new MsgObject();
        if (removeByIds) {
            msgObject.setMsg("批量删除成功");
            msgObject.setCode(1);
        } else {
            msgObject.setMsg("批量删除失败");
            msgObject.setCode(2);
        }
        return msgObject;
    }
}

